package com.app.web;

import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;

import com.app.common.listener.UserOnlineListener;
import com.app.util.AjaxResult;
import com.app.util.AuthUtils;
import com.app.util.Const;
import com.app.util.MyUtil;
import com.app.web.adimin.model.Menu;
import com.app.web.adimin.model.User;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;


public class IndexController extends BaseController{
	
	public void index(){
		this.render("index.html");
	}
	
	public void admin(){
		String type = this.getPara("type","");
		if("login".equals(type)){
			AjaxResult result = new AjaxResult(1,"success");
			String name=this.getPara("username");
			String pwd=this.getPara("password");
			try{
				User user=User.dao.getByEmailAndPwd(name, DigestUtils.md5Hex(pwd));
				if(user==null){
					result.setMsg(0, "login failed：username or password error!");
				}else{
					this.getSession().setAttribute("online", new UserOnlineListener(user));
					this.getSession().setAttribute(Const.CURRENT_USER, user);
					this.setCookie(Const.AUTH_TOKEN, AuthUtils.getCookieAuthToken(this.getRequest(), user), Const.COOKIE_AGE);
				}
			}catch(Exception e){
				e.printStackTrace();
				result.setMsg(0, "login failed："+e.getMessage());
			}finally{
				this.renderJson(result.toJson());
			}
		}else{
			User user=this.getSessionAttr("current_user");//当前用户
			String view="dashboard.html";
			if(user!=null){
				//查询权限顺序-- user ——》user_role ——》role ——》 menu_role ——》 menu
				int t=0;
				if(t==0){
					//查出用户所有权限
					List<Record> urList=MyUtil.getList("user_role", "user_id", user.get("id", "0")+"","role_id",false);
					int maxRole=3;//用户最高权限
					if(urList.size()>0){
						maxRole=urList.get(0).getInt("role_id");
						this.setAttr("maxRole", maxRole);//设置最高权限
						this.setSessionAttr("urList", urList);//把用户所有权限存入session中
					}
					if(maxRole<=2){
						//根据权限查出所有角色
						String urIDs=MyUtil.getStr(urList,"role_id");
						List<Record> rList=MyUtil.getList("role", "id", urIDs,null,false);
						
						//根据角色权限查出所有菜单权限（id）
						String rIDs=MyUtil.getStr(rList,"id");
						List<Record> mrList=MyUtil.getList("menu_role", "role_id", rIDs,null,false);;
						
						//根据所有菜单权限(menu_id)查出所有菜单
						String mIDs=MyUtil.getStr(mrList,"menu_id");;
						List<Menu> mList=Menu.dao.findMenuByIds(mIDs);
						List<Record> list=Menu.dao.getMenuTree(mList);//获得树形list
						this.setAttr("mList", MyUtil.getSort(list, "id", true));
					}else{
						view="index.html";
					}
				}else{
					int role=Integer.parseInt(user.get("type", "5")+"");
					List<Menu> mList=Menu.dao.findMenuById(role*1000);
					List<Record> list=Menu.dao.getMenuTree(mList);

					this.setAttr("maxRole", role);
					this.setAttr("mList", list);
				}
				this.setAttr("user", user);
				this.render(view);
			}else{
				this.render("login.html");
			}
		}
	}
	
	public void login(){
		AjaxResult result = new AjaxResult(1,"登陆成功");
		try {
			User user0 = this.getModel(User.class).setAttrs(this.getParamMap());
			User user = User.dao.getByEmailAndPwd(user0.getStr("email"), DigestUtils.md5Hex(user0.getStr("password")));
			if(user == null ){
				result.setMsg(0, "用户名或密码错误!");
			}else{
				this.getSession().setAttribute("online", new UserOnlineListener(user));
				this.getSession().setAttribute(Const.CURRENT_USER, user);
				this.setCookie(Const.AUTH_TOKEN, AuthUtils.getCookieAuthToken(this.getRequest(), user), Const.COOKIE_AGE);
				result.setData("user", user);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg(0, "登陆失败："+e.getMessage());
		}finally{
			this.renderJson(result.toJson());
		}
	}
	
	public void logout(){
		//AjaxResult result = new AjaxResult(1);
		this.getSession().invalidate();
		this.removeCookie("auth_token");
		
		String type=this.getPara("type","");
		if("admin".equals(type)){
			this.render("login.html");
		}else{
			this.render("index.html");
		}
		
		//this.renderJson(result.toJson());
		
	}
	
	@Deprecated
	public void account(){
		AjaxResult result = new AjaxResult(1);
		Record record = new Record();
		record.set("site_view_count", Const.SITE_VIEW_ACOUNT);
		record.set("topic_count", Db.queryLong("select count(1) from topic"));
		record.set("user_count", Db.queryLong("select count(1) from user"));
		record.set("newer", Db.findFirst("select user_name,id as user_id from user order by id desc limit 1"));
		record.set("cates", Db.find("SELECT * FROM category"));//所有话题类型
		
		result.setData("info", record);

		this.renderJson(result.toJson());
	}
	
}








